<template>
  <el-upload
    class="avatar-uploader"
    :class="fileList.length < limit ? '' : 'restrict-uploader'"
    v-model:file-list="fileList"
    action="#"
    :limit="limit"
    list-type="picture-card"
    :auto-upload="false"
    :on-preview="handlePictureCardPreview"
  >
    <el-icon>
      <Plus />
    </el-icon>
  </el-upload>

  <el-dialog v-model="avatarVisible">
    <img w-full :src="avatarImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const fileList = ref<UploadUserFile[]>([])

defineProps<{
  size: string // 上传窗口大小
  limit: number // 物理层限制文件上传数量
}>()

const avatarVisible = ref(false) // 头像大图预览弹框
const avatarImageUrl = ref() // 头像大图预览地址

// 图片预览
const handlePictureCardPreview: UploadProps['onPreview'] = (file) => {
  avatarImageUrl.value = file.url
  avatarVisible.value = true
}

// 文件列表暴露给父组件
defineExpose({
  fileList
})
</script>

<style lang="scss" scoped>
.avatar-uploader {
  :deep(.el-upload-list--picture-card) {
    --el-upload-list-picture-card-size: v-bind(size);
  }

  :deep(.el-upload--picture-card) {
    --el-upload-picture-card-size: v-bind(size);
  }
}

.restrict-uploader {
  :deep(.el-upload) {
    display: none;
  }
}
</style>
